<?php
/**
 * Created by PhpStorm.
 * User: ytlmi
 * Date: 2018/2/2
 * Time: 19:12
 */

namespace app\forensic\controller;

use app\common\controller\BaseController;
use org\util\forensicTool\CODISDecode;

class Sample extends BaseController
{
    protected $model = 'app\forensic\model\Sample';

    /**
     * @return mixed
     */
    public function importGenotype()
    {
        try {
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('file');
            // 移动到框架应用根目录/public/uploads/ 目录下
            if ($file) {
                //保存文件
                $savePath = $_SERVER['DOCUMENT_ROOT'] . DS . 'uploads' . DS . 'codis';
                $info = $file->move($savePath);
                $filePath = $savePath . DS . $info->getSaveName();
                //解析文件
                $genotypes = CODISDecode::instance()->loadFile($filePath)->decode();
                //保存分型
                $count_update = 0;
                $count_add = 0;
                foreach ($genotypes as $sampleName => $genotype) {
                    if ($this->M->get(['sample_name' => $sampleName])) {//样品存在，更新
                        $this->M->get(['sample_name' => $sampleName])->save(['genotype' => $genotype]);
                        $count_update++;
                    } else {//样品不存在，添加
                        $this->M->save(['sample_name' => $sampleName, 'genotype' => $genotype]);
                        $count_add++;
                    }
                }
                return [$count_add, $count_update];
            } else {
                return [];
            }
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

}